using Godot;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public partial class SettingView : WindowBase
{
	// Called when the node enters the scene tree for the first time.
	private Button saveBtn;
	private Button loadBtn;
	private Button deletetBtn;
	private ItemList dataList;
	private TextureRect textureRect;

	private int chooseDataIndex;
	private List<string> saveDataList = new List<string>();

	public override void init()
	{
		base.init();
		saveBtn = GetNode<Button>("SaveBtn");
		loadBtn = GetNode<Button>("LoadBtn");
		dataList = GetNode<ItemList>("DataList");
		textureRect = GetNode<TextureRect>("TextureRect");
		deletetBtn = GetNode<Button>("DeleteBtn");

		saveBtn.Pressed += onSavePressed;
		loadBtn.Pressed += onLoadPressed;
		deletetBtn.Pressed += OnDeletePressed;
		dataList.ItemSelected += OnClickItem;
	}



	public override void onShow()
	{
		base.onShow();

		//加载存储数据




		updateView();


	}

	private void updateView()
	{
		saveDataList.Clear();
		saveDataList = SaveAndLoadManager.getInstance().SaveItemList;

		dataList.Clear();
		foreach (var data in saveDataList)
		{

			dataList.AddItem(data);

		}

		chooseDataIndex = -1;

		loadBtn.Disabled = true;
		deletetBtn.Disabled = true;

		textureRect.Texture = null;
	}

	private void onSavePressed()
	{
		closeThisWindow(closeToSave);



	}

	private async void closeToSave()
	{
		await Task.Delay(100);
		SaveAndLoadManager.getInstance().Save();

	}

	private void onLoadPressed()
	{
		if (chooseDataIndex > -1)
		{
			SaveAndLoadManager.getInstance().Load(chooseDataIndex);
			closeThisWindow();
			GD.Print("加载成功");
		}

	}

	private void OnClickItem(long index)
	{
		if (chooseDataIndex != (int)index)
		{
			loadBtn.Disabled = false;
			deletetBtn.Disabled = false;
			chooseDataIndex = (int)index;
			textureRect.Texture = SaveAndLoadManager.getInstance().GetScreenShotByName(saveDataList[chooseDataIndex]);
		}


	}

	private void OnDeletePressed()
	{
		if (chooseDataIndex > -1)
		{
			SaveAndLoadManager.getInstance().DeleteSaveDataByName(saveDataList[chooseDataIndex]);
			//更新列表
			updateView();
		}
	}
}
